package v1

import (
	"encoding/json"
	"net/http"
	"rustdesk_api_server/api/request"
	"rustdesk_api_server/api/response"
	"rustdesk_api_server/api/services"
	"rustdesk_api_server/models"
	"time"

	"github.com/gin-gonic/gin"
)

type AddressBook struct{}

func (api *AddressBook) Get(ctx *gin.Context) {
	user_id := ctx.GetInt("user_id")

	data := services.AddressBook.ExportAll(uint(user_id))
	var result response.AddressBookResult
	if data == "" {
		result.Data = "{}"
	} else {
		result.Data = data
	}
	result.Error = false
	result.UpdateAt = time.Now().Format("2006-01-02 15:04:05")
	ctx.JSON(http.StatusOK, result)
}

func (api *AddressBook) Update(ctx *gin.Context) {
	var form request.AddressBookUpdateForm
	if err := ctx.ShouldBindJSON(&form); err != nil {
		ctx.AbortWithStatusJSON(http.StatusOK, gin.H{
			"code":  -1,
			"error": "请求参数异常",
		})
		return
	}
	data := request.AddressBookUpdateFormData{}
	if err := json.Unmarshal([]byte(form.Data), &data); err != nil {
		ctx.AbortWithStatusJSON(http.StatusOK, gin.H{
			"error": "请求数据异常",
		})
		return
	}

	var user models.User
	user_id := ctx.GetInt("user_id")
	user.ID = uint(user_id)

	services.AddressBook.DeleteAll(user)

	services.AddressBook.UpdateTags(uint(user_id), data)

	services.AddressBook.UpdatePeers(uint(user_id), data)

	ctx.JSON(http.StatusOK, response.JsonResult{
		Data: "success",
	})
}
